import re

import os

from sqlalchemy import create_engine
from sqlalchemy.sql import text

from mtp.model import *

import logging 
log = logging.getLogger(__name__)

engine = None

def convert_content(body):
    def image_repl(mo):
        return "<<image %s>>" % mo.group(1)
    body = re.sub(r"\[\[Image\((.*?),.*\)\]\]", image_repl, body)

    def link_repl(mo):
        return '[[%s|%s]]' % (mo.group(1), mo.group(2))
    body = re.sub(r"\[wiki:(.*?) (.*?)\]", link_repl, body)

    def header_repl(mo):
        return "%s %s" % (mo.group(1), mo.group(2).strip())
    body = re.sub(r"(={1,4})(.*?)={1,4}", header_repl, body)

    def bold_repl(mo):
        return "**%s**" % mo.group(1)
    body = re.sub(r"'''(.*?)'''", bold_repl, body)

    def italic_repl(mo):
        return "//%s//" % mo.group(1)
    body = re.sub(r"''(.*?)''", italic_repl, body)

    def monospace_repl(mo):
        return "##%s##" % mo.group(1)
    body = re.sub(r"{{{(.*?)}}}", monospace_repl, body)
    body = re.sub(r"`(.*?)`", monospace_repl, body)

    def superscript_repl(mo):
        return "^^%s^^" % mo.group(1)
    body = re.sub(r"\^(.*?)\^", superscript_repl, body)

    def list_repl(mo):
        return "%s %s" % ("*"*len(mo.group(1)), mo.group(2))
    body = re.sub(r"(?m)^( +)\*(.*)", list_repl, body)

    body = body.replace('[[PageOutline]]', '<<toc>>')
    #body = body.replace('[[', '<<')
    #body = body.replace(']]', '>>')
    #body = body.replace('[wiki:', '[')
    return body


def convert_page(name, path):
    log.info("page %s --------------------------" % name)
    r = engine.execute(text("select text from wiki where name='%s' order by version DESC limit 1" % name))
    t = r.fetchone()[0]
    t = convert_content(t)
    page, page_rev = Page.add(name, t, 'imported')
    
    from mtp.lib.plugins.attachments import Attachment

    localdir = os.path.join(path, "attachments", "wiki", name)
    log.debug('attachment dir %s' % localdir)
    if os.path.exists(localdir):
        for fn in os.listdir(localdir):
            fullpath = os.path.join(localdir, fn)
            Attachment.createForPage(page, fn, open(fullpath))


def convert_all(path):
    global engine 
    db = os.path.join(path, 'db', 'trac.db')
    log.debug('trac db path %s' % db)
    engine = create_engine('sqlite:///%s' % db, echo=False)

    r = engine.execute(text("select name from wiki group by name")) 
    for result in r:
        convert_page(result[0], path)

